<?php
namespace app\weixin\model;

use think\Model;
use think\Db;
class Cart extends Model
{
    protected $table = 'wx_cart';

    //添加到购物车
    public function addCart($data)
    {
        //获取会员id
        $uid = session('uid');
        $oldshopmsg = $this->where(['user_id'=>$uid])->find();
        //判断购物车是否为空
        if(!$oldshopmsg)
        {

            $msg['user_id'] = $uid;

            $newarr = [];
            $newarr[$data['id']] = $data;
            $newarr = json_encode($newarr);
            $msg['goods_msg'] = $newarr;
            $this->save($msg);
            return 1;


            }else{
            $msg['user_id'] = $uid;

            $newarr = [];
            $newarr[$data['id']] = $data;
            $newarr = json_encode($newarr);
            $msg['goods_msg'] = $newarr;
            $this->save($msg);
            return 1;

        }
    }

    //查询购物车
    public function selectCart()
    {
        //获取会员id
        $uid = session('uid');
        //查询购物车信息
        return   $oldshopmsg = $this->where(['user_id'=>$uid])->select();

    }
    //从购物车中移除
    public function removeCart($id)
    {
        //获取会员id
        $uid = session('user.id');
        //查询购物车信息
        $oldshopmsg = $this->where(['user_id'=>$uid])->find();
        $shopmsg = $oldshopmsg['goods_msg'];
        $shopmsg = json_decode($shopmsg,true);
        $arr = explode(',',$id);
        $flag = true;
        foreach ($arr as $key=>$value){
            unset($shopmsg[$value]);
            if($shopmsg[$value]){
                $flag = false;
            }
        }
        if($shopmsg)
        {
            $shopmsg = json_encode($shopmsg);
            $oldshopmsg['goods_msg'] = $shopmsg;
            $this->save($oldshopmsg);
        }else{
            $this->where(['user_id'=>$uid])->delete();
        }
        $result = $flag ? 1:0;
        return $result;
    }

}